package org.example.mq.brokerserver;

import com.sun.net.httpserver.HttpServer;
import org.example.mq.brokerserver.core.BasicProperties;
import org.example.mq.common.*;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//BrokerServer就是消息队列的服务器
//本质上是一个Tcp服务器
public class BrokerServer {
    private ServerSocket serverSocket = null;
    //TODO现在是只有一个虚拟主机的情况
    private VirtualHost virtualHost = new VirtualHost("default");
    //这个哈希表用来存当前所有的会话
    //key为channelId，value为对应的Socket对象
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    //引入线程池来处理多个客户端请求
    private ExecutorService executorService = null;
    //引入一个boolean变量控制服务器是否继续运行
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException{
        System.out.println("[BrokerServer] 启动！");
        executorService = Executors.newCachedThreadPool();//根据需要创建新的线程或者复用已经有的线程。
        try{
            while(runnable){
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑丢给这个线程池
                executorService.submit(()->{
                   processConnection(clientSocket);
                });
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器停止运行！");
        }
    }



    //这里采用一个单独的停止方法来用于单元测试
    public void stop() throws IOException {
        runnable = false;
        executorService.shutdownNow();
        serverSocket.close();
    }
    //通过这个方法来处理一个客户端的连接
    //在这一个连接中可能涉及多个请求和响应
    private void processConnection(Socket clientSocket) {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //这里按照特定的格式来读取并解析
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while (true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.把响应写给客户端
                    writeResponse(dataOutputStream, response);
                }
            }
        }catch (EOFException | SocketException e){
                //借助这个异常来退出循环
                System.out.println("[BrokerServer] connection 关闭！客户端的地址："+clientSocket.getInetAddress().toString()
                +": "+clientSocket.getPort());
            } catch (IOException | ClassNotFoundException | MqException e) {
                System.out.println("[BrokerServer] connection 出现异常！");
                e.printStackTrace();
            }finally {
                try{
                    clientSocket.close();
                    clearClosedSession(clientSocket);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
    }

    private void clearClosedSession(Socket clientSocket) {
        List<String> toDeleteChannelId = new ArrayList<>();
        for(Map.Entry<String,Socket> entry : sessions.entrySet()){
            if(entry.getValue() == clientSocket){
                //集合类不可以边遍历边删除
                toDeleteChannelId.add(entry.getKey());
            }
        }
        for(String channelId : toDeleteChannelId){
            sessions.remove(channelId);
        }
        System.out.println("[BrokerServer] 清理session完成！ 清理的sessionId："+toDeleteChannelId);
    }

    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
        System.out.println("[BrokerServer] 响应已经发送！Type="+response.getType()+",Length="+response.getLength());
    }

    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException,MqException {
        //先解析payload
        BasicArguments basicArguments = (BasicArguments) BinaryTool.toObject(request.getPayload());
        System.out.println("[Request] rid="+basicArguments.getRid() + ",channelId="+basicArguments.getChannelId()
        +",type="+request.getType()+",length="+request.getLength());
        boolean ok = true;
        //根据type的值判断接下来要干什么
        if(request.getType()==0x1){
            sessions.put(basicArguments.getChannelId(),clientSocket);
            System.out.println("[BrokerServer] 创建channel完成！channelId = "+basicArguments.getChannelId());
        }else if(request.getType()==0x2){
            sessions.remove(basicArguments.getChannelId());
            System.out.println("[BrokerServer] 销毁channel完成！channelId = "+basicArguments.getChannelId());
        }else if(request.getType()==0x3){
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(arguments.getExchangeName(),arguments.getExchangeType(),arguments.isDurable(),arguments.isAutoDelete(),arguments.getArgument());
        }else if(request.getType()==0x4){
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());
        }else if(request.getType()==0x5){
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),arguments.isDurable(),arguments.isExclusive(),arguments.isAutoDelete(),arguments.getOptions());
        } else if (request.getType()==0x6) {
            QueueDeleteArguments arguments = (QueueDeleteArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType()==0x7) {
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType()==0x8) {
            QueueUnbindingArguments arguments = (QueueUnbindingArguments) basicArguments;
            ok = virtualHost.queueUnbinding(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType()==0x9) {
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType()==0xa) {
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(),
                    new Consumer() {
                        @Override
                        public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] payload) throws MqException, IOException {
                            //这里实现将消息发给对应的客户端
                            Socket clientSocket = sessions.get(consumerTag);
                            if(clientSocket==null||clientSocket.isClosed()){
                                throw new MqException("[BrokerServer] 订阅消息的客户端不存在或关闭！");
                            }
                            //构造数据
                            SubScribeReturnArguments subScribeReturnArguments = new SubScribeReturnArguments();
                            subScribeReturnArguments.setChannelId(consumerTag);
                            subScribeReturnArguments.setRid("");
                            subScribeReturnArguments.setOk(true);
                            subScribeReturnArguments.setConsumeTag(consumerTag);
                            subScribeReturnArguments.setBasicProperties(basicProperties);
                            subScribeReturnArguments.setPayload(payload);
                            byte[] body = BinaryTool.toBytes(subScribeReturnArguments);
                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(body.length);
                            response.setPayload(body);
                            //将数据写回给客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(dataOutputStream,response);
                        }
                    });
        } else if (request.getType()==0xb) {
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        }else {
            throw new MqException("[BrokerServer] 发生错误！未知的类型，type="+request.getType());
        }
        //构造响应
        BasicReturnArguments basicReturnArguments = new BasicReturnArguments();
        basicReturnArguments.setChannelId(basicArguments.getChannelId());
        basicReturnArguments.setOk(ok);
        basicReturnArguments.setRid(basicArguments.getRid());
        byte[] payload = BinaryTool.toBytes(basicReturnArguments);
        Response response = new Response();
        response.setType(request.getType());
        response.setPayload(payload);
        response.setLength(payload.length);
        System.out.println("[Response] rid="+basicReturnArguments.getRid()+",channelId="+basicReturnArguments.getChannelId()
        +",type="+response.getType()+",length="+response.getLength());
        return response;
    }

    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());
        request.setLength(dataInputStream.readInt());
        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if(n!=request.getLength()){
            throw new IOException("读取请求格式出错！");
        }
        request.setPayload(payload);
        return request;
    }
}
